package org.ws.edu.task2;

import org.ws.edu.task2.exceptions.ExtensionLengthException;
import org.ws.edu.task2.exceptions.IncorrectPathException;
import org.ws.edu.task2.exceptions.IncorrectSymbolsException;
import org.ws.edu.task2.exceptions.NameLengthException;

public class VirtualFileSystem {

    private static VirtualFileSystem instance;
    private Element rootElement = null;
    private Element currentElement = null;

    private VirtualFileSystem() {
        currentElement = rootElement = new Element("C:", true);
    }

    public static VirtualFileSystem getInstance() {
        if (instance == null) {
            instance = new VirtualFileSystem();
        }
        return instance;
    }

    public Element getElementByPath(String[] path) throws ExtensionLengthException, NameLengthException, IncorrectSymbolsException,
            IncorrectPathException {
        Validator.checkElementsNames(path);
        Element element = rootElement;
        if (path.length == 2) {
            return element;
        }
        for (int i = 1; i < path.length - 1; i++) {

            if (element.elements.contains(new Element(path[i], true))) {
                element = element.elements.ceiling(new Element(path[i], true));
            } else {
                throw new IncorrectPathException();
            }
        }
        return element;

    }

    public Element getRootElement() {
        return rootElement;
    }

    public boolean containElement(Element name) {
        return currentElement.elements.contains(name);
    }

    public void removeElement(Element name) {
        currentElement.elements.remove(name);
    }

    public void addElement(Element name) {
        currentElement.elements.add(name);
    }

    public void changeCurrentElement(Element name) {
        currentElement = name;
    }

    public boolean isCurrentFolder(Element name) {
        return currentElement.equals(name);
    }

    public Element getCurrentFolder() {
        return currentElement;
    }
}
